package st.business.tepth.business.taskallocation.modifytrouble;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import st.business.tepth.base.OnDataConvertListener;
import st.business.tepth.business.bean.TroubleClassificationBean;
import st.business.tepth.config.ItemFields;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * Author: shadow
 * Email:  1025431817@qq.com
 * Time:   2019-07-24 19:35
 */

public class ModifyTroubleModel implements ModifyTroubleContract.Model {

    @Override
    public Disposable getTroubleList(String token, int repairId,
                                     final OnDataConvertListener<List<MultipleItemEntity>> listener) {
        return RxRestClient.builder()
                .url(Url.GetTroubleClassification)
                .params("token", token)
                .params("repairId", repairId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        listener.convert(convertToTaskList(response));
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        listener.error(code, msg);
                    }
                })
                .build()
                .post();
    }

    @Override
    public Disposable modifyTroubleClassification(final String token, final int repairId, int phenomenonId,
                                                  int targetSeriesId,
                                                  final OnDataConvertListener<String> listener,
                                                  final OnDataConvertListener<List<MultipleItemEntity>>
                                                          dataListener) {
        return RxRestClient.builder()
                .url(Url.ModifyTroubleClassification)
                .params("token", token)
                .params("phenomenonId", phenomenonId)
                .params("targetSeriesId", targetSeriesId)
                .build()
                .flatPost()
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<String, ObservableSource<String>>() {
                    @Override
                    public ObservableSource<String> apply(String response) throws Exception {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String ResultMsg = jsonObject.getString("msg");
                        if (ResultCode == 0) {
                            //成功
                            if (listener != null) {
                                listener.convert("");
                            }
                            return RxRestClient.builder()
                                    .url(Url.GetTroubleClassification)
                                    .params("repairId", repairId)
                                    .params("token", token)
                                    .build()
                                    .onlyPost();
                        } else {
                            return Observable.error(new Throwable(ResultMsg));
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver<String>() {

                    @Override
                    public void onNext(String response) {
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        int ResultCode = jsonObject.getInteger("code");
                        String object = jsonObject.getString("data");
                        String ResultMsg = jsonObject.getString("msg");
                        if (ResultCode == 0) {
                            if (dataListener != null) {
                                dataListener.convert(convertToTaskList(object));
                            }
                        } else {
                            listener.error(ResultCode, ResultMsg);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.error(-1, e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private List<MultipleItemEntity> convertToTaskList(String response) {
        List<TroubleClassificationBean> dataList = new ObjConverter<List<TroubleClassificationBean>>().convert(response
                , new TypeReference<List<TroubleClassificationBean>>() {
                });
        List<MultipleItemEntity> entityList = new ArrayList<>();
        if (dataList != null) {
            int position = 0;
            for (TroubleClassificationBean bean : dataList) {
                List<TroubleClassificationBean.ClassBean> classBeans =
                        bean.getVehicleSeriesList();
                MultipleItemEntity entityHead = MultipleItemEntity.builder()
                        .setItemType(ModifyTroubleAdapter.TYPE_0)
                        .setField("vehicleSeriesId", bean.getVehicleSeriesId())
                        .setField("name", bean.getName())
                        .setField("id", bean.getId())
                        .setField("position", -1)
                        .setField("children", classBeans)
                        .build();
                entityList.add(entityHead);
                position++;
                if (classBeans != null) {
                    for (TroubleClassificationBean.ClassBean classBean : classBeans) {
                        entityList.add(MultipleItemEntity.builder()
                                .setItemType(ModifyTroubleAdapter.TYPE_1)
                                .setField(ItemFields.ITEM_OBJ, classBean)
                                .setField("headEntity", entityHead)
                                .build());
                        if (classBean.isSelected()) {
                            entityHead.setField("position", position);
                        }
                        position++;
                    }
                }
            }
        }
        return entityList;
    }
}
